using System;

namespace sforceExplorer
{

	/// <summary>
	/// Summary description for SOQLPlus.
	/// </summary>
	public class SOQLPlus
	{
		public delegate void ConfirmDeleteRecords(int numberToDelete, sforce.QueryResult qr);
		public delegate void DeleteCompleted(int numberDeleted);
		public delegate void CommandNotSupported(string commandType);

		public event ConfirmDeleteRecords ConfirmDeleteRecordsEvent;
		public event DeleteCompleted DeleteCompletedEvent;
		public event CommandNotSupported CommandNotSupportedEvent;

		public SOQLPlus()
		{
			//
			// TODO: Add constructor logic here
			//
		}

		public void DoConfirmedDelete(sforce.QueryResult qr) 
		{
			bool loopAgain = true;
			int numberDeleted = 0;
			int timeout = Utility.binding.Timeout;
			Utility.binding.Timeout = System.Threading.Timeout.Infinite;
			while (loopAgain) 
			{
				string[] ids = new string[qr.records.Length];
				for (int i=0;i<ids.Length;i++) 
				{
					ids[i] = qr.records[i].Id;
					numberDeleted += 1;
				}
				
			
				Utility.binding.delete(ids);
				if (qr.done)
					loopAgain = false;
				else
					qr = Utility.binding.queryMore(qr.queryLocator);
			}
			Utility.binding.Timeout = timeout;
			OnDeleteCompleted(numberDeleted);
		}

		private void OnCommandNotSupported(string commandType) 
		{
			if (CommandNotSupportedEvent != null) 
				CommandNotSupportedEvent(commandType);
		}
		private void OnDeleteCompleted(int numberDeleted) 
		{
			if (DeleteCompletedEvent != null) 
				DeleteCompletedEvent(numberDeleted);
		}
		private void OnConfirmDeleteRecords(int numberToDelete, sforce.QueryResult qr) 
		{
			if (ConfirmDeleteRecordsEvent != null) 
				ConfirmDeleteRecordsEvent(numberToDelete, qr);
		}
		public void doDelete(string command) 
		{
			string fromObject;
			command = command.Trim();
			string tempCommand = command;

			if (command.EndsWith(";"))
				tempCommand = command.Substring(0, command.Length - 1);
			fromObject = tempCommand.Substring(tempCommand.ToLower().IndexOf("from") + 4).Trim();
			//fromObject = tempCommand.Substring(0, tempCommand.IndexOf(" ")).Trim();
			string where = null;
			if (tempCommand.ToLower().IndexOf(" where ") > -1)
			{
				fromObject = fromObject.Substring(0, fromObject.IndexOf(" ")).Trim();
				where = tempCommand.Substring(tempCommand.IndexOf(" where ") + 6).Trim();
			}
			string sql = "Select Id From " + fromObject;
			if (where != null) 
				sql = sql + " where " + where;

			sforce.QueryResult qr = Utility.binding.query(sql);
			if (qr.size > 0) 
			{
				this.OnConfirmDeleteRecords(qr.size, qr);
			}
		}
		public void ExecuteCommand(string command) 
		{
			try 
			{
				string commandType = command.Substring(0, command.IndexOf(" "));
				if (commandType.Trim().ToLower().Equals("delete"))
					doDelete(command);
				else
					OnCommandNotSupported(commandType);
			} 
			catch (Exception e) 
			{
				OnCommandNotSupported("unknown");
				System.Diagnostics.Trace.WriteLine(e.Message);
			}
		}
	}
}
